package leetcode.剑指offer.剑指II;

import org.junit.Test;

/**
 * @author :songyaozhang
 * @date :Created 2021/9/10 14:30
 * @description :
 */
public class 剑指_II_12_左右两边子数组的和相等 {
  @Test
  public void test() {
    Solution solution = new Solution();
    System.out.println(solution.pivotIndex(new int[]{2, 1, -1}));
  }


  // 1 8 11 17 22 28
  //输入：nums = [1,7,3,6,5,6]
    class Solution {
        public int pivotIndex(int[] nums) {
          int n = nums.length;
          if (n == 0 || n == 1) return -1;
          int[] sums = new int[n];
          sums[0] = nums[0];
          for (int i = 1; i < nums.length; i++) {
            sums[i] = nums[i] + sums[i - 1];
          }
          int tail = sums[n - 1];
          int left, right;
          for (int i = 0; i < sums.length; i++) {
            if (i == 0) {
              left = 0;
            } else {
              left = sums[i - 1];
            }
            if (i == n - 1) {
              right = 0;
            } else {
              right = tail - sums[i];
            }
            if (left == right) return i;
          }
          return -1;
        }
    }


}
